﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EzDesk.Apps.Model.Staff;
using EzDesk.Clients.DesktopWeb.StaffService;
using EzDesk.Core.Model;
using EzDesk.Utility.Log;
using EzDesk.Utility.Web.Controllers;
using EzDesk.Utility.Web.Extensions;
using EzDesk.Utility.Web.ServiceReference;
using EzDesk.Utility;
using Webdiyer.WebControls.Mvc;
using EzDesk.Utility.ServiceStatusInfo;

namespace EzDesk.Clients.DesktopWeb.Controllers
{
    public class StaffController : EzDeskAppController
    {
        static IStaffService StaffService
        {
            get { return ServiceReferenceFactory<IStaffService, StaffServiceClient>.GetService(); }
        }
        private const string UpdateFailed = "更改失败！";
        private const string UpdateSuccess = "更改成功！";
        private const string ExceptionType = "[DesktopWeb - Staff]";


        #region [ private methods ]
        private IEnumerable<ContactModel> getStaffInfoQuery(string memberString)
        {
            // TODO: Check result.
            var staffInfosList = StaffService.GetContactInfos(memberString).Result;

            var staffUserInfoDic = EzApiClient
                .GetSimpleUserInfos(
                    staffInfosList
                        .Select(p => p.UserId.ToString())
                        .ToArray()
                        .Join(","))
                .ToDictionary(simpleUser => simpleUser.Id);

            return staffInfosList
                .Select(contactInfo => new ContactModel()
                {
                    TargetUser = staffUserInfoDic[contactInfo.UserId],
                    ContactInfo = contactInfo
                });
        }
        private StatusInfo updateContactInfo(Guid targetUserId, string qqNumber, string mobileNo, string mainEmail)
        {
            //todo: 验证参数
            var newStaffInfo = new ContactInfo()
            {
                UserId = targetUserId,
                QqNumber = qqNumber,
                MobileNo = mobileNo,
                MainEmail = mainEmail
            };

            return StaffService.UpdateContactInfo(newStaffInfo);
        }

        private string getIconTypeByImageStream(byte[] buffer)
        {

            var fileClass = buffer[0].ToString() + buffer[1].ToString();
            var iconType = "";
            //todo: 其他格式 
            switch (fileClass)
            {
                case "255216":
                    iconType = "JPEG";
                    break;
                case "13780":
                    iconType = "PNG";
                    break;
            }
            return iconType;
        }

        #endregion

        #region [ page methods ]
        /// <summary>
        /// 员工联系通讯录
        /// </summary>
        /// <param name="id">id表示查看的当前页数</param>
        /// <returns></returns>
        [Authorize]
        public ActionResult ContactBook(int? id, Guid? userId, Guid? deptId)
        {
            string memberString = "";
            if (deptId.HasValue)
            {
                //如果有deptId 获取dept memberString  
                var groupId = EzApiClient.GetDeptById(deptId.Value).GroupId;
                memberString = EzApiClient.GetGroupById(groupId.GetValueOrDefault(Guid.Empty)).Memberstring;
            }
            else
            {
                //如果没有 默认 everyone
                memberString = "everyone";
            }

            IEnumerable<ContactModel> contactQuery = getStaffInfoQuery(memberString);

            // 处理分页
            int pageIndex = 1;
            if (id.HasValue)
            {
                pageIndex = id.Value;
            }
            else if (userId.HasValue)
            {
                // 处理制定了UserId的情况，跳转到目标页面
                var index = contactQuery
                    .TakeWhile(contactModel => contactModel.TargetUser.Id != userId.Value)
                    .Count();
                pageIndex = index / 5 + 1;

                ViewData["UserId"] = userId.ToJson();
            }

            var contactBox = contactQuery.AsQueryable().ToPagedList(pageIndex, 5);

            if (Request.IsAjaxRequest())
            {
                return PartialView("_staffList", contactBox);
            }

            ViewData["DeptList"] = EzApiClient.GetAllDepts().ToJson();
            ViewData["AllContactInfo"] = contactBox;

            return View();
        }

        /// <summary>
        /// 我的联系信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public ActionResult MyContactInfo(Guid? userId)
        {
            if (!userId.HasValue)
            {
                userId = CurrentUserId;
            }

            var myStaffInfo = StaffService.GetContactInfoByUserId(userId.Value).Result;

            ViewData["CurrentUser"] = EzApiClient.GetSimpleUserById(CurrentUserId).ToJson();
            ViewData["StaffInfos"] = myStaffInfo.ToJson();

            return View();
        }

        [Authorize]
        public ActionResult Staff(Guid? userId)
        {
            var memberstring = "everyone";
            var staffList = getStaffInfoQuery(memberstring);

            ViewData["UserId"] = userId.HasValue ? userId.Value.ToJson() : null;
            ViewData["StaffList"] = staffList.ToList().ToJson();
            return View();
        }

        [HttpGet]
        [Authorize]
        public ActionResult AddUser()
        {
            ViewData["DeptList"] = EzApiClient.GetAllDepts().ToJson();
            return View();
        }

        //[HttpPost]
        [Authorize]
        public ActionResult DoCheckUserExist(string userName)
        {
            userName = userName.ToLower();
            var users = EzApiClient.GetSimpleUserInfos("everyone").ToList();
            var simpleUser = users.FirstOrDefault(user=>user.UserName.ToLower() == userName);
            return Json(simpleUser == null);
        }

        [HttpGet]
        [Authorize]
        public ActionResult EditStaff(Guid userId)
        {
            var staffInfo = new
            {
                TargetUser = EzApiClient.GetSimpleUserById(userId),
                ContactInfo = StaffService.GetContactInfoByUserId(userId).Result,
            };
            ViewData["DeptList"] = EzApiClient.GetAllDepts().ToJson();
            ViewData["StaffInfo"] = staffInfo.ToJson();
            return View();
        }

        #endregion


        #region [ Ajax Methods ]


        [HttpPost]
        [Authorize]
        public ActionResult DoUpdateContactInfo(Guid userId, string qqNumber, string mobileNo, string mainEmail)
        {
            //todo: 判断参数

            var statusInfo = updateContactInfo(userId, qqNumber, mobileNo, mainEmail);
            if(statusInfo.Status == ServiceStatus.Success)
            {
                statusInfo.Info = "更新联系方式完成";
            }
            return Json(statusInfo, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        [Authorize]
        public ActionResult DoUpdatePwd(Guid userId, string oldPassword, string newPassword)
        {
            EzApiClient.ChangePassword(userId, oldPassword, newPassword);
            var statusInfo = new StatusInfo("密码更新成功完成。");
            return Json(statusInfo);
        }

        [HttpPost]
        [Authorize]
        public ActionResult DoUpdateBasicInfo(Guid userId, string name, Guid deptId)
        {
            UserProfile userProfile = EzApiClient.GetUserProfileById(userId);
            userProfile.Name = name;
            userProfile.DeptId = deptId;
            EzApiClient.UpdateUserProfile(userProfile);
            var statusInfo = new StatusInfo("更新基本信息完成。");
            return Json(statusInfo);
        }

        [HttpPost]
        public ActionResult DoImageUpload(Guid userId)
        {
            //todo: 写成ajax方法，加入上传图片判错，缩图等功能
            var statusInfo = new StatusInfo();

            // 直接向服务器写入新的图片文件
            if (Request.Files != null && Request.Files.Count > 0)
            {
                var file = Request.Files[0];
                if (file != null)
                {
                    var length = file.ContentLength;
                    var buffer = new byte[length];
                    file.InputStream.Read(buffer, 0, length);
                    var iconTypeStr = getIconTypeByImageStream(buffer);

                    EzApiClient.UpdateHeadIcon(userId, buffer, iconTypeStr);

                    statusInfo.Info = "成功修改头像";
                }
                else
                {
                    statusInfo = new StatusInfo(ServiceStatus.Error, "选择文件出错");
                }
            }else
            {
                statusInfo = new StatusInfo(ServiceStatus.Error, "选择文件出错");
            }
            return Json(statusInfo);
        }

        [HttpPost]
        [Authorize]
        public JsonResult DoAddUser(string name, Guid deptId, string userName, string pwd, string qqNumber, string mobileNo, string mainEmail)
        {
            var statusInfo = new StatusInfo();
            var newUserProfile = new UserProfile()
                                     {
                                         Id = Guid.NewGuid(),
                                         DeptId = deptId,
                                         Name = name,
                                         PositionId = null,
                                         UserCode = userName
                                     };
            Guid? newUserId = EzApiClient.CreateNewUser(newUserProfile, pwd);

            var updateStatusInfo = new StatusInfo();
            if (newUserId.HasValue)
            {
                updateStatusInfo = updateContactInfo(newUserId.Value, qqNumber, mobileNo, mainEmail);
            }
            if (updateStatusInfo.Status == ServiceStatus.Success)
            {
                statusInfo.Info = string.Format("添加新用户成功，欢迎新同事 {0}", name);
                statusInfo.Data = new { UserId = newUserId.ToString() };
            }

            return Json(statusInfo);
        }

        #endregion

    }
}
